//串口相关的头文件
#include <stdio.h>  /*标准输入输出定义*/
#include <stdlib.h> /*标准函数库定义*/
#include <unistd.h> /*Unix 标准函数定义*/
#include <sys/types.h>
#include <sys/stat.h>
#include "nativeUartFun.h"
#include <arpa/inet.h>
#include <string.h>
#include "public.h"

pthread_mutex_t modbusRecvDataTreatLock;
void modbusRecDataTreat(INT16U CommIdx, INT16U recLen, char *recBuf)
{
	pthread_mutex_lock(&modbusRecvDataTreatLock);
	//DebugPrint("CommIdx=%d,recLen=%d\n", CommIdx, recLen);
	DebugPrint("\n");
	int i = 0;
	for (i = 0; i < recLen; i++)
	{
		DebugPrint(" %x", recBuf[i]);
	}
	DebugPrint("\n");
	int calCrc = modbusCrc16(recBuf, recLen - 2);
	int recCrc = (int)recBuf[recLen - 2] * 256 + (int)recBuf[recLen - 1];
	DebugPrint(" calCrc =%x ;recCrc =%x \n", calCrc, recCrc);
	if (calCrc != recCrc)
	{
		DebugPrint(" modbus recieve crc err \n");
		goto end;
	}

	for (i = 0; i < g_mbPollTabLen; i++)
	{
		if (g_mbPollTab[i].comPacketIndex != CommIdx)
			continue;
		DebugPrint("g_mbPollTab[i].oid=%d \n", g_mbPollTab[i].oid);
		if (g_mbPollTab[i].len <= 2)
		{
			if (g_mbPollTab[i].bitIndex == 0xff)
			{
				Word4Byte temp;
				memcpy(&temp, &recBuf[g_mbPollTab[i].byteIndex - 1], 2);
				temp.word = htons(temp.word);
				if(g_mbPollTab[i].adjustFlag !=0 && g_mbPollTab[i].rwFlag ==0)
				{
					temp.word=temp.word*g_mbPollTab[i].multiValue/g_mbPollTab[i].devideValue+g_mbPollTab[i].addSubValue;
				}
				memcpy(&g_mbPollTab[i].devValue[0], &temp, 2);
				DebugPrint("g_mbPollTab[i].devValue[0]=%x ;devValue[1]=%x ;\n", g_mbPollTab[i].devValue[0], g_mbPollTab[i].devValue[1]);
			}
			else
			{
				int temp = recBuf[g_mbPollTab[i].byteIndex - 1] & g_mbPollTab[i].bitIndex;
				if (temp)
					g_mbPollTab[i].devValue[0] = 1;
				else
					g_mbPollTab[i].devValue[0] = 0;
			}
		}
		else if (g_mbPollTab[i].len < recLen)
		{
			int idx = g_mbPollTab[i].mbLongDataAtListStartAddr;
			memcpy(&g_mbLongDataList[idx], &recBuf[g_mbPollTab[i].byteIndex - 1], g_mbPollTab[i].len);
		}
		//g_mbPollTab[i].devValue=0;
	}

end:
	pthread_mutex_unlock(&modbusRecvDataTreatLock);
}

void modbusSetResposeDataTreat(INT16U oid, INT8U cmd,INT8U recLen, char *recBuf)
{
	DebugPrint("\n");
	int i = 0;
	for (i = 0; i < recLen; i++)
	{
		DebugPrint(" %x", recBuf[i]);
	}
	DebugPrint("\n");
	int calCrc = modbusCrc16(recBuf, recLen - 2);
	int recCrc = (int)recBuf[recLen - 2] * 256 + (int)recBuf[recLen - 1];
	DebugPrint("set packet calCrc =%x ;recCrc =%x \n", calCrc, recCrc);
	if (calCrc != recCrc)
	{
		DebugPrint(" modbus recieve crc err \n");
		goto end;
	}
	int temp;
	if(cmd ==0x05)
	{
		if(recBuf[4]==0xff &&recBuf[5]==0)temp=1;
		else if(recBuf[4]==0 &&recBuf[5]==0)temp=0;
		else goto end;
		DebugPrint("set recive value =%d \n",temp);
	}
	else if(cmd ==0x06)
	{
		temp=recBuf[4]*256+recBuf[5];
		DebugPrint("set recive value =%d \n",temp);
	}
	set_mbOidDevValue(oid, (INT8U *)&temp);

	end:
		return;
}